package com.ble.lightscreen;

import android.app.Notification;
import android.app.NotificationChannel;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.Service;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.pm.PackageManager;
import android.net.Uri;
import android.os.Build;
import android.os.IBinder;
import android.os.PowerManager;
import android.support.v4.app.NotificationCompat;
import android.util.Log;
import android.widget.ArrayAdapter;

import java.util.ArrayList;
import java.util.Timer;
import java.util.TimerTask;

public class BleLightService extends Service {
    private long scantime;
    private long waketime;
    private static String addr;
    private String url;
    private String pname;
    public static ArrayAdapter<String> adapter = null;
    //创建容器，用于数据传递
    private ArrayList<String> bledata = new ArrayList<>();
    private ArrayList<String> bledata_compare = new ArrayList<>(); //用于比较
    private BluetoothAdapter bleadapter = BluetoothAdapter.getDefaultAdapter();//获取蓝牙适配器
    private static String result;
    private static int count;
    private boolean open;
    private Context mContext;
    Notification notification;
    PowerManager pm;
    PowerManager.WakeLock wl;
    PowerManager.WakeLock wl2;
    public String getResult() {
        return result;
    }

    public int getCount() {
        return count;
    }

    public void setAddr(String addr) {
        this.addr = addr;
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onCreate() {
        // 获取电源管理器对象
        pm = (PowerManager) this.getSystemService(this.POWER_SERVICE);
        wl = pm.newWakeLock(PowerManager.ACQUIRE_CAUSES_WAKEUP |
                PowerManager.SCREEN_BRIGHT_WAKE_LOCK, "i:ScreenOn");
        wl2 = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, "i:CPUOn");
        //蓝牙数据传递
        adapter = new ArrayAdapter<>(this,android.R.layout.simple_list_item_1, this.bledata);
        IntentFilter filter = new IntentFilter(BluetoothDevice.ACTION_FOUND);
        registerReceiver(receiver, filter);
        bledata_compare = new ArrayList<>(); //用于比较
        }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        mContext = this;

        String CHANNEL_ID = "com.ble.lightscreen";
        String CHANNEL_NAME = "BleLight";
        NotificationChannel notificationChannel = null;
        if(Build.VERSION.SDK_INT>=Build.VERSION_CODES.O){
            notificationChannel = new NotificationChannel(CHANNEL_ID, CHANNEL_NAME, NotificationManager.IMPORTANCE_HIGH);
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notificationManager.createNotificationChannel(notificationChannel);
        }
        //初始化数据
        init();
        //通知栏占用，防杀后台
        Intent notificationIntent = new Intent(this, MainActivity.class);
        PendingIntent pendingIntent = PendingIntent.getActivity(mContext, 0,
                notificationIntent, PendingIntent.FLAG_UPDATE_CURRENT);
        notification = new NotificationCompat.Builder(mContext,CHANNEL_ID)
                .setSmallIcon(R.drawable.ic_launcher_background)
                .setWhen(System.currentTimeMillis())
                .setTicker("蓝牙亮屏")
                .setContentTitle("后台保活")
                .setContentText("确保熄屏后台运行，误关")
                .setOngoing(true)
                .setPriority(Notification.PRIORITY_MAX)
                .setContentIntent(pendingIntent)
                .setAutoCancel(false)
                .build();
        /*使用startForeground,如果id为0，那么notification将不会显示*/
        startForeground(100, notification);
        //开始扫描蓝牙
        //定时器间隔一段时间执行蓝牙扫描和对比
        Timer timer = new Timer();
        timer.schedule(new TimerTask(){
            public void run(){
                //清空上一次的数据，进行新一轮的扫描
                bledata.clear();
                bledata_compare.clear();
                //初始化蓝牙控件
                initView();
            }

        }, 0,scantime);
        return START_NOT_STICKY;
    }

    //初始化数据
    public void init(){
        Log.i("zxlc", "init()");
        Conf con = new Conf();
        //判断是否初始化，如果没有就向配置文件写入数据
        if (con.getConfigProperties("addr").equals("")){
            con.writeDateToLocalFile("scantime", "20");
            con.writeDateToLocalFile("url", "");
            con.writeDateToLocalFile("pname","");
            con.writeDateToLocalFile("addr","F1:99:F1:2C:C6:59");
        }
        //从配置文件读取数据
        url = con.getConfigProperties("url");
        pname = con.getConfigProperties("pname");
        addr = con.getConfigProperties("addr");
        scantime = Long.parseLong(con.getConfigProperties("scantime"))*1000;//秒转为毫秒
        waketime = Long.parseLong(con.getConfigProperties("scantime"))*1000;
    }
    //初始化蓝牙控件
    private void initView(){
        //开启蓝牙
        if(!bleadapter.isEnabled()){
            bleadapter.enable();
        }
        //开始扫描
        bleadapter.startDiscovery();
    }

    //蓝牙数据回传接口
    private final BroadcastReceiver receiver = new BroadcastReceiver() {
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                String deviceName = device.getName();
                String deviceHardwareAddress = device.getAddress();
                if(bledata_compare.contains(device.getAddress())) {
                }   //若列表中已经有了相应设备信息，则不添加进去
                else {
                    bledata_compare.add(device.getAddress());// 蓝牙MAC地址
                    bledata.add( "address:"+deviceHardwareAddress+"\n"+"name:"+deviceName);
                    Log.i("xp扫描到", ""+bledata_compare.size());
                    count = bledata_compare.size();
                    adapter.notifyDataSetChanged();
                }
                if (bledata_compare!=null && device.getAddress().equals(addr)){
                    Log.i("xp","点亮屏幕"+addr);
                    wakeUpAndUnlock();
                    result = "点亮屏幕";
                    if (!url.equals("")&&open){
                        OpenUrl(url);
                    }
                    if(!pname.equals("")&&open){
                        OpenApp(pname);
                    }
                    open = false;
                }else {
                    wl2.setReferenceCounted(false);
                    //占用cpu，保持后台运行
                    wl2.acquire();

                    Log.i("xp","熄灭屏幕");
                    result = "熄灭屏幕";
                    open = true;
                }
            }
        }
    };
    //唤醒屏幕
    private void wakeUpAndUnlock() {

        if (wl2.isHeld()) {//如果已获得唤醒锁但尚未释放，则返回true。
            wl2.release();
        }
//            wl2.setReferenceCounted(false);
             // 点亮屏幕，取得唤醒锁，在waketime毫秒之后释放锁熄灭屏幕。
            wl.acquire(waketime+5000);
    }
    //使用默认浏览器打开设置的url
    private void OpenUrl(String url){
        Intent intent =  new  Intent();
        intent.setAction( "android.intent.action.VIEW" );
        Uri content_url = Uri.parse(url);
        intent.setData(content_url);
        startActivity(intent);
    }
    //打开设置的app
    private void OpenApp(String pname){
        PackageManager packageManager = getPackageManager();
        Intent intent = packageManager.getLaunchIntentForPackage(pname);
        startActivity(intent);
    }

    @Override
    public void onDestroy() {
        Intent intent = new Intent(this,BleLightService.class);
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            this.startForegroundService(intent);
        } else {
            this.startService(intent);
        }
        Log.i("xp","停止服务");
        unregisterReceiver(receiver);
    }
}
